package com.liguang.rcs.admin.service;

import com.google.common.collect.Sets;
import com.liguang.rcs.admin.db.entity.DodmsPermissionEntity;
import com.liguang.rcs.admin.db.repository.DodmsPermissionRepository;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Slf4j
@Service
public class DodmsPermissionService {

    @Autowired
    private DodmsPermissionRepository repository;

    public Set<String> queryByRoleId(Long... roleIds) {
        Set<String> permissions = Sets.newHashSet();
        if(roleIds == null || roleIds.length == 0){
            return permissions;
        }
        List<DodmsPermissionEntity> permissionList = repository.findByRoleIdIn(Arrays.asList(roleIds));

        for(DodmsPermissionEntity permission : permissionList){
            permissions.add(permission.getPermission());
        }
        return permissions;
    }


    public boolean checkSuperPermission(Long roleId) {
        if(roleId == null){
            return false;
        }

        Optional<DodmsPermissionEntity> entity = repository.findById(roleId);

        return entity.isPresent()
                && "*".equals(entity.get().getPermission())
                && (entity.get().getDeleted() == null || !entity.get().getDeleted());
    }

    @Transactional
    public void deleteByRoleId(Long roleId) {
        Optional<DodmsPermissionEntity> entity = repository.findById(roleId);
        if (!entity.isPresent()) {
            return;
        }
        DodmsPermissionEntity dodmsPermissionEntity = entity.get();
        dodmsPermissionEntity.setDeleted(true);
        repository.save(dodmsPermissionEntity);
    }

    public void add(DodmsPermissionEntity permission) {
        if (permission != null && permission.getId() == null) {
            repository.save(permission);
            return;
        }
        log.info("save fail, permission is invalid, permission:{}", permission);
    }
}
